package com.fivefaces.ide.plugins;

import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import org.jetbrains.annotations.Nls;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;

/**
 * User: abdullahkhan
 * Date: 13/09/12
 * Time: 6:19 PM
 */
public class Configuration implements Configurable {
    private JComponent rootPanel;
    private TextFieldWithBrowseButton browseButton;
    private final String currentExecutablePath;
    private final ConsoleExecutablePathService pathService;

    public Configuration() throws IOException {
        pathService = ConsoleExecutablePathServiceFactory.getInstance();
        currentExecutablePath = pathService.findPath();
        FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT);
        rootPanel = new JPanel(flowLayout);
        rootPanel.add(new Label("Console executable path"));
        browseButton = new TextFieldWithBrowseButton();
        browseButton.addBrowseFolderListener("Console executable path", "Console executable path", null, FileChooserDescriptorFactory.createSingleFolderDescriptor());
        browseButton.setEditable(true);
        browseButton.setText(currentExecutablePath);
        rootPanel.add(browseButton);
    }

    @Nls
    @Override
    public String getDisplayName() {
        return "Show Console";
    }

    @Override
    public Icon getIcon() {
        return null;
    }

    @Override
    public String getHelpTopic() {
        return "Show Console";
    }

    @Override
    public JComponent createComponent() {
        return rootPanel;
    }

    @Override
    public boolean isModified() {
        return true;
    }

    @Override
    public void apply() throws ConfigurationException {
        String path = browseButton.getTextField().getText();
        if (currentExecutablePath != null && path != null) {
            try {
                pathService.save(path);
            } catch (Exception e) {
                System.err.println("Failed to save changes.");
                e.printStackTrace();
            }
            System.err.println("Saved to path - " + path);
        }
    }

    @Override
    public void reset() {

    }

    @Override
    public void disposeUIResources() {
    }
}
